<template>
  <div></div>
</template>

<script setup lang="ts">
  import Dexie, { type EntityTable } from 'dexie'

  interface User {
    id: number
    username: string
    age: number
    userType: string
    sort: number
    email: string
  }

  const db = new Dexie('database') as Dexie & {
    // id 是主键
    user: EntityTable<User, 'id'>
  }

  db.version(1).stores({
    // 设置主键为 id 自增
    user: '++id'
  })

  // 添加数据
  async function addUser(user: Omit<User, 'id'>) {
    const res = await db.user.add(user)

    console.log('添加数据成功', res)
  }

  addUser({ username: 'kunkun', age: 18, userType: 'user', sort: 10, email: 'ikun@qq.com' })
  // 删除数据
  async function deleteUser(id: number) {
    const res = await db.user.delete(id)
    console.log('删除数据成功', res)
  }
  // deleteUser(5)

  // 清空数据
  async function clearUser() {
    const res = await db.user.clear()
    console.log('清空数据成功', res)
  }

  // 修改数据
  async function updateUser(id: number, user: Partial<Omit<User, 'id'>>) {
    const res = await db.user.update(id, user)
    console.log('更新数据成功', res)
  }

  updateUser(1, { username: '坤坤', userType: 'admin1' })

  async function getUser(id: number) {
    const res = await db.user.get(id)
    console.log('获取数据成功', res)
  }

  // getUser(1)

  // 获取所有数据
  async function getAllUser() {
    const res = db.user.orderBy('sort').toArray()
    console.log('获取所有数据成功', res)
  }

  // 删除数据库
  async function delDB() {
    db.close()
    const res = await db.delete()
    console.log('删除数据库成功', res)
  }

  // setTimeout(() => {
  //   delDB()
  // }, 3000)
</script>

<style scoped></style>
